package com.efounder.frame.fragment.attendance;

import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilemanager.R;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zhangshunyun on 2017/5/18.
 * <p>
 * 考勤应用号打卡Fragment
 * 使用了sdk辅助H5进行定位
 */

public class EFWorkCardFragment extends EFFragment {

    private WebView mWebView;
    private String userId;
    private String nickName;
    private String userName;
    private String passWord;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ef_dk_attendance, container, false);
        mWebView = (WebView) view.findViewById(R.id.dk_webview);
        mWebView.clearCache(true);
        mWebView.setWebViewClient(new WebViewClient() {//对https支持
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        getInformation();
        initAMap();
        //允许JavaScript执行
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheMaxSize(10 * 1024 * 1024);
        //webview定位相关设置  
        settings.setGeolocationEnabled(true);
        settings.setDomStorageEnabled(true);
        mWebView.setVerticalScrollBarEnabled(false);//垂直不显示滚动条   
        mWebView.addJavascriptInterface(new JavaScriptInterface(), "OSPPlugin");
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });
        mWebView.loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "OSPMobileLiveApp" + "/" + userId + "/Apps/3289/html/EF_PunchCard.html");
//        mWebView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mWebView.loadUrl("file://"+Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"OSPMobileLiveApp"+"/"+userId+"/Apps/3289/html/EF_PunchCard.html");
//
//          }
//        },500);
        return view;
    }

    private void initAMap() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity().getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //开启 SDK 辅助H5定位功能
        mLocationClient.startAssistantLocation();
        //启动定位
        mLocationClient.startLocation();
    }

    private void getInformation() {
        //132
        userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        nickName = EnvironmentVariable.getProperty(Constants.KEY_NICK_NAME);
        userName = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        passWord = EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD);
//        Toast.makeText(getActivity(), userId+nickName+userName+passWord, Toast.LENGTH_SHORT).show();
    }

    public class JavaScriptInterface {

        public JavaScriptInterface() {

        }

        @JavascriptInterface
        public String getUserInfo() throws JSONException {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("passWord", passWord);
            jsonObject.put("IMUserName", userId);
            jsonObject.put("IMPassWord", passWord);
            jsonObject.put("nickName", nickName);
            return jsonObject.toString();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWebView.clearCache(true);
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }
}
